package cn.ycc1.service;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author ycc
 * @date 2025/5/12
 */
public class Producer {
    private static final String BROKER_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "DEMO_QUEUE";

    public static void main(String[] args) {
        try {
            // 1. 创建连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);

            // 2. 创建连接
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // 3. 创建会话 (不启用事务，自动确认)
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // 4. 创建目标队列
//            Destination destination = session.createQueue(QUEUE_NAME);
            // 将 createQueue 改为 createTopic
            Destination destination = session.createTopic("DEMO_TOPIC");

            // 5. 创建生产者
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 非持久化消息

            // 6. 创建并发送消息
            for (int i = 1; i <= 10; i++) {
                TextMessage message = session.createTextMessage("Hello ActiveMQ! 这是消息 #" + i);
                producer.send(message);
                System.out.println("发送消息: " + message.getText());
            }

            // 7. 关闭连接
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
